import sys
import os
import time
import smtplib

def sendMail(status, ycr, parentA, parentB, progenyRange, contact):
	try:
        	msg = {}
        	me = "jlin@systemsbiology.net"#= the sender's email address
        	msg['Subject'] = status + ' Progeny range %s created %s' % (progenyRange, ycr)
        	msg['From'] = "jlin@systemsbiology.net"
        	msg['To'] = contact
        	text = msg['Subject']
        	m = "From: %s\r\nTo: %s\r\nSubject: %s\r\nX-Mailer: My-Mail\r\n\r\n" % (me, contact, msg['Subject'])
        	s = smtplib.SMTP('mailhost.systemsbiology.net')
        	s.sendmail(msg['From'], [me,contact], m+text)
        	s.quit()
		return '{"status":"200"}'
	except Exception as inst:
		return inst

tetradCount = 1
strainsPerPlate = -1
strainsPerTetrad = 4

def executeSH(cmd):
	os.system(cmd)

def getSiblings(key):
	global strainsPerTetrad
	if (strainsPerTetrad == 1):
		return "";
	remainder = (key-1)%strainsPerTetrad
	if (remainder == 0):
		return "'YPG%20" + str(key + 1) + "_YPG%20" + str(key + 2) + "_YPG%20" + str(key + 3) + "'"
	elif (remainder == 1):
		return "'YPG%20" + str(key - 1) + "_YPG%20" + str(key + 1) + "_YPG%20" + str(key + 2) + "'"
	elif (remainder == 2):
		return "'YPG%20" + str(key - 1) + "_YPG%20" + str(key - 2) + "_YPG%20" + str(key + 1) + "'"
	else:
		return "'YPG%20" + str(key - 1) + "_YPG%20" + str(key - 2) + "_YPG%20" + str(key - 3) + "'"

def translateRow(offset):
	global strainsPerPlate
	if (offset <= 12):
		return "A"
	if (offset <= 24):
		return "B"
	if (offset <= 36):
		return "C"
	if (offset <= 48):
		return "D"
	if (offset <= 60):
		return "E"
	if (offset <= 72):
		return "F"
	if (offset <= 84):
		return "G"
	if (offset <= strainsPerPlate):
		return "H"

def translateTetradRow():
	if (tetradCount%10 == 0):
		return 10
	return tetradCount%10

def translatePosition(key, boxnum, start, iteration):
	row = translateRow(iteration)
	col = iteration%12 
	if (col == 0):
		col = 12
	return row + str(col)	

def translateBoxNumber(ycr, start, key):
	global strainsPerPlate
	begin = 1
	realkey = key - start
	return realkey/strainsPerPlate + begin

def translatePlateNumber(iteration, start):
	plateNum = 6
	strainsPerPlate = 80
	return plateNum + (iteration/strainsPerPlate)

def encodeSpace(str):
	return str.replace(' ', '%20')

#python POST.py "http://ravioli:8080/addama-rest/dudley-sample/path/datasource/YPG/YPG%209999/create?JSON={genotype:'ggg',crossingRef:'YCR%208'}"
def generateYPGCSV(crosskey, start, end, perPlate, parentAKey, parentAlphaKey, perTetrad, logwriter):
	global tetradCount, strainsPerPlate, strainsPerTetrad
	logwriter.write("\nstart generate ypg csv\n")
	sh_ypgfile = open('./%s_YPG%s_curl.sh' %('load', crosskey +str(start)),'w')
	strainsPerPlate = perPlate
	strainsPerTetrad = int(perTetrad)
	sh_ypgfile.write("#!/bin/bash\n")
	ypgcsv = open(crosskey + "_YPG_" + str(start) + ".csv", "w")
	ypgcsv.write("ypgKey,ypgMatingType,ypgGenotype,ypgParentA,ypgParentAlpha,ypgSiblings,ypgCrossingRef,ypgBoxNumber,ypgPosition,ypgDateFrozen,ypgComments,ypgTetrad,ypgStatus\n")
	offset = 1
	for ypgkey in range(start, end+1):
		iteration = ypgkey - offset
		if (offset == strainsPerPlate+1):
			offset = 1
		boxnum = translateBoxNumber(crosskey, start, ypgkey)
		tetrad = (offset-1)/strainsPerTetrad + 1
		ypgcsv.write('"YPG' + str(ypgkey) + '",' + '"Undetermined","","' + parentAKey + '","' + parentAlphaKey + '","","' + crosskey + '",' + crosskey + "-" + str(boxnum) + '",' + '"' + translatePosition(ypgkey, boxnum, start, offset) + '","11/14/2011","comments","' + str(tetrad) + '","Viable"\n')
		offset += 1
	ypgcsv.close()
	ccmd = "curl 'http://ravioli:8080/solr/update/csv?commit=true' --data-binary @" + ypgcsv.name + " -H 'Content-type:text/plain; charset=utf-8'"
	logwriter.write("cmd%s\n" %ccmd)
	sh_ypgfile.write(ccmd + "\n")
	shcmd = 'sh ' + sh_ypgfile.name
	sh_ypgfile.close()
	executeSH("sh " + sh_ypgfile.name + " >& load_YPGYCR132269_curl.out")
	logwriter.write("done with generation\n")
	return

def main(ycr, parentA, parentB, progenyCount, ypgStart, perPlate, perTetrad, plateLabel, contact, logwriter):
	try:
		maintime = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
		ypgStart = int(ypgStart)
		qend = ypgStart + int(progenyCount)-1
		perPlate = int(perPlate)
		logwriter.write("Generate csv for %i-%i %s" %(ypgStart,qend,maintime))
		generateYPGCSV(ycr, ypgStart, qend, perPlate, parentA, parentB, perTetrad, logwriter)
		progenyRange = str(ypgStart) + ":" + str(ypgStart + int(progenyCount))		
		logwriter.write("Prep email " + progenyRange + "\n")
		sendMail("SUCCESS", ycr, parentA, parentB, progenyRange, contact)
		logwriter.write("SMTP mail sent\n")		
	except:
		sendMail("ERROR", ycr, parentA, parentB, ycr, contact)
		logwriter.write("Error:", sys.exc_type)
		return -1

if __name__ == "__main__":
	print "__main__ place holder"
